<template>
  <div class="sample-manage-container">
    <el-card class="sample-manage-card">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="搜索">
            <el-input
              v-model="searchForm.keyword"
              placeholder="标题/描述"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="公开性">
            <el-select
              class="status-search"
              v-model="searchForm.is_public"
              placeholder="选择"
              clearable
            >
              <el-option label="公开" :value="true" />
              <el-option label="不公开" :value="false" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="success" @click="handleAdd">添加样片</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 样片列 -->
      <div class="sample-grid">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" v-for="item in sampleList" :key="item.id">
            <el-card class="sample-card" :body-style="{ padding: '0px' }">
              <div class="image-wrapper">
                <el-image :src="item.photos?.[0]" fit="cover" class="sample-image" />
                <div class="overlay">
                  <div class="stats">
                    <span
                      ><el-icon><Star /></el-icon> {{ item.likes }}</span
                    >
                  </div>
                </div>
              </div>
              <div class="sample-info">
                <h3 class="title">{{ item.title }}</h3>
                <div class="tags">
                  <el-tag v-for="tag in item.tags" :key="tag" size="small" class="custom-tag">
                    {{ tag }}
                  </el-tag>
                </div>
                <div class="photographer">摄影师：{{ item.photographer.nickname }}</div>
                <div class="status-row">
                  <el-tag :type="item.is_public ? 'success' : 'info'" size="small">
                    {{ item.is_public ? '公开' : '不公开' }}
                  </el-tag>
                </div>
                <div class="actions">
                  <el-button type="primary" link @click="handleEdit(item)"> 编辑 </el-button>
                  <el-button type="success" link @click="handleManageImages(item)">
                    图片管理
                  </el-button>
                  <el-button
                    :type="item.is_active ? 'danger' : 'success'"
                    link
                    @click="handleToggleStatus(item)"
                  >
                    {{ item.is_active ? '下架' : '发布' }}
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[12, 24, 36, 48]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 编辑对话框 -->
      <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑样片' : '添加样片'" width="600px">
        <el-form ref="formRef" :model="editForm" :rules="rules" label-width="100px">
          <el-form-item label="标题" prop="title">
            <el-input v-model="editForm.title" />
          </el-form-item>

          <el-form-item label="标签" prop="tags">
            <el-select
              v-model="editForm.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请输入标签"
            >
              <el-option v-for="tag in tagOptions" :key="tag" :label="tag" :value="tag" />
            </el-select>
          </el-form-item>

          <el-form-item label="摄影师" prop="photographer_id">
            <el-select v-model="editForm.photographer_id">
              <el-option
                v-for="item in photographers"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="拍摄日期" prop="shooting_date">
            <el-date-picker
              v-model="editForm.shooting_date"
              type="date"
              placeholder="选择拍摄日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>

          <el-form-item label="公开性" prop="isPublic">
            <el-switch
              v-model="editForm.is_public"
              :active-text="'公开'"
              :inactive-text="'不公开'"
            />
          </el-form-item>

          <el-form-item label="描述" prop="description">
            <el-input v-model="editForm.description" type="textarea" :rows="3" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSave" :loading="saveLoading"> 保存 </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 图片管理对话框 -->
      <el-dialog v-model="imagePreviewDialogVisible">
        <img w-full :src="imagePreviewDialogImageUrl" alt="Preview Image" />
      </el-dialog>

      <el-dialog v-model="imageDialogVisible" title="图片管理" width="800px">
        <div v-loading="uploadLoading" class="upload-container">
          <el-upload
            class="image-uploader"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-change="handleImageChange"
            :before-upload="beforeUpload"
            :file-list="photosList"
            multiple
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </div>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="imageDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSaveImages" :loading="saveLoading">
              保存
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Plus, View, Star } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { Sample, SampleQuery } from '@/types/sample'
import {
  getSamplesList,
  createSample,
  updateSample,
  updateSampleStatus,
  updateSamplePhotos,
} from '@/api/sample'
import { beforeUpload } from '@/utils/upload'
import type { FileItem, UploadFile } from '@/types/upload'
import { v4 as uuidv4 } from 'uuid'
import { uploadSamples } from '@/api/upload'
import Logger from '@/utils/logger'
import type { UploadUserFile } from 'element-plus'
import { getPhotographersList } from '@/api/photographer'
import type { Photographer } from '@/types/photographer'

// 标签选项
const tagOptions = ref([
  '室内',
  '室外',
  '海景',
  '森系',
  '古风',
  '韩式',
  '欧式',
  '小清新',
  '复古',
  '奢华',
  '简约',
  '创意',
])

// 搜索表单
const searchForm = reactive<SampleQuery>({
  keyword: '',
  is_public: undefined,
  page: 1,
  pageSize: 12,
})

// 摄影师列表
const photographers = ref<Photographer[]>([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 加载状态
const loading = ref(false)
const saveLoading = ref(false)

// 对话框相关
const imagePreviewDialogImageUrl = ref('')
const imagePreviewDialogVisible = ref(false)
const dialogVisible = ref(false)
const imageDialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()

// 编辑表单
const editForm = reactive<Partial<Sample>>({
  id: 0,
  title: '',
  description: '',
  tags: [],
  is_public: true,
  photos: [],
  shooting_date: undefined,
  photographer_id: undefined,
})

// 图片管理相关
const uploadLoading = ref(false)
const photosList = ref<UploadUserFile[]>([])

// 表单验证规则
const rules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  photographer_id: [{ required: true, message: '请选择摄影师', trigger: 'change' }],
  shooting_date: [{ required: true, message: '请选择拍摄时间', trigger: 'change' }],
  tags: [{ required: true, message: '请选择标签', trigger: 'blur' }],
  description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
})

// 样片列表数据
const sampleList = ref<Sample[]>([])

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.is_public = undefined
  handleSearch()
}

// 处理分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchData()
}

// 添加样片
const handleAdd = () => {
  isEdit.value = false
  Object.assign(editForm, {
    title: '',
    description: '',
    tags: [],
    photographer_id: undefined,
    shooting_date: undefined,
    is_public: true,
    photos: [],
  })
  dialogVisible.value = true
}

// 编辑样片
const handleEdit = (row: Sample) => {
  isEdit.value = true
  Object.assign(editForm, {
    id: row.id,
    title: row.title,
    description: row.description,
    tags: [...row.tags],
    photographer_id: row.photographer_id,
    shooting_date: row.shooting_date,
    is_public: row.is_public,
    photos: [...(row.photos ?? [])],
  })
  dialogVisible.value = true
}

// 管理图片
const handleManageImages = (row: Sample) => {
  editForm.id = row.id
  // 将现有图片转换为 UploadUserFile 格式
  if (row.photos) {
    photosList.value = row.photos?.map((url, index) => {
      return {
        name: `图片${index + 1}`,
        url: url,
      } as UploadUserFile
    })
  }
  imageDialogVisible.value = true
}

const handleRemove = (file: UploadUserFile) => {
  const index = photosList.value.findIndex((item) => item.url === file.url)
  if (index > -1) {
    photosList.value.splice(index, 1)
  }
}

const handlePictureCardPreview = (file: UploadUserFile) => {
  imagePreviewDialogImageUrl.value = file.url!
  imagePreviewDialogVisible.value = true
}

// 切换状态
const handleToggleStatus = async (row: Sample) => {
  try {
    await ElMessageBox.confirm(`确定要${row.is_active ? '下架' : '发布'}该样片吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await updateSampleStatus(row.id)
    ElMessage.success('操作成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 处理图片上传
const handleImageChange = (file: UploadFile) => {
  if (!beforeUpload(file.raw)) return

  // 创建预览URL
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = async () => {
    const newFile: FileItem = {
      uid: uuidv4(),
      name: file.name,
      url: reader.result as string,
      status: 'ready',
      raw: file.raw,
    }

    try {
      if (!newFile.raw) {
        ElMessage.error('请选择文件')
        return
      }

      newFile.status = 'uploading'
      newFile.percentage = 0

      const response = await uploadSamples([newFile.raw], (percentage) => {
        newFile.percentage = percentage
      })

      newFile.status = 'success'
      photosList.value.push({
        name: response.data.data.files[0].filename,
        url: response.data.data.files[0].url,
      } as UploadUserFile)
      ElMessage.success('上传成功')
    } catch (error) {
      newFile.status = 'error'
      ElMessage.error('上传失败')
      Logger.error('上传失败', error)
    }
  }
}

// 保存图片
const handleSaveImages = async () => {
  saveLoading.value = true
  try {
    const uploadPhotos = photosList.value.map((item) => item.url!)
    const response = await updateSamplePhotos(editForm.id!, {
      photos: uploadPhotos,
    })
    Logger.info('保存图片成功', response)
    ElMessage.success('保存成功')
    imageDialogVisible.value = false
    fetchData()
  } catch (error) {
    Logger.error('保存图片失败', error)
    ElMessage.error('保存失败')
  } finally {
    saveLoading.value = false
  }
}

// 保存样片信息
const handleSave = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      try {
        if (isEdit.value) {
          await updateSample(editForm.id!, {
            title: editForm.title,
            description: editForm.description,
            tags: editForm.tags,
            is_public: editForm.is_public,
            shooting_date: editForm.shooting_date!,
            photographer_id: editForm.photographer_id,
          })
        } else {
          await createSample({
            title: editForm.title!,
            description: editForm.description!,
            tags: editForm.tags!,
            is_public: editForm.is_public!,
            shooting_date: editForm.shooting_date!,
            photographer_id: editForm.photographer_id!,
          })
        }
        ElMessage.success('保存成功')
        dialogVisible.value = false
        fetchData()
      } catch (error) {
        ElMessage.error('保存失败')
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const { data } = await getSamplesList({
      keyword: searchForm.keyword,
      is_public: searchForm.is_public,
      page: currentPage.value,
      pageSize: pageSize.value,
    })
    sampleList.value = data.data.items
    total.value = data.data.meta.total
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const fetchPhotographers = async () => {
  try {
    const { data } = await getPhotographersList()
    photographers.value = data.data.items
  } catch (error) {
    ElMessage.error('获取摄影师列表失败')
  }
}

onMounted(() => {
  fetchData()
  fetchPhotographers()
})
</script>

<style scoped>
.sample-manage-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  min-height: calc(100vh - 200px);
  box-sizing: border-box;
}

.sample-manage-card {
  margin-top: 0;
}

.search-bar {
  margin-bottom: 20px;
}

.sample-grid {
  margin: 20px 0;
}

.sample-card {
  margin-bottom: 20px;
  transition: transform 0.3s;
}

.sample-card:hover {
  transform: translateY(-5px);
}

.image-wrapper {
  position: relative;
  width: 100%;
  padding-top: 75%;
  overflow: hidden;
}

.sample-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.3);
  opacity: 0;
  transition: opacity 0.3s;
  display: flex;
  align-items: flex-end;
  padding: 10px;
  box-sizing: border-box;
}

.sample-card:hover .overlay {
  opacity: 1;
}

.stats {
  color: white;
  display: flex;
  gap: 15px;
}

.stats span {
  display: flex;
  align-items: center;
  gap: 5px;
}

.sample-info {
  padding: 15px;
}

.title {
  margin: 0 0 10px 0;
  font-size: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tags {
  margin-bottom: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.custom-tag {
  margin-right: 5px;
}

.photographer {
  color: #666;
  font-size: 13px;
  margin-bottom: 10px;
}

.status-row {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.actions {
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #eee;
  padding-top: 10px;
  margin-top: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.image-uploader {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

:deep(.el-upload--picture-card) {
  width: 150px;
  height: 150px;
  line-height: 150px;
}

.status-search {
  width: 100px;
}

.upload-container {
  min-height: 200px;
}

.upload-progress {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.progress-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.progress-item:last-child {
  margin-bottom: 0;
}

.filename {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
